﻿using System;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

namespace winS.UnityEditor.ProcessEditor
{
    public class NodeSearchGroup : NodeSearchItem
    {
        private static readonly string[] splitCacheArray = new string[2];

        private readonly List<NodeSearchEntry> searchEntryList = new List<NodeSearchEntry>();
        private readonly Dictionary<string, NodeSearchGroup> searchGroupDictionary = new Dictionary<string, NodeSearchGroup>();

        private SearchTreeGroupEntry cache;

        public NodeSearchGroup(string name, int level) : base(name, level)
        {
        }

        public void Add(Type processType, string path, Type type)
        {
            if (SplitOnce(path))
            {
                string groupName = splitCacheArray[0];
                if (!searchGroupDictionary.TryGetValue(groupName, out NodeSearchGroup nodeSearchGroup)) searchGroupDictionary.Add(groupName, nodeSearchGroup = new NodeSearchGroup(groupName, level + 1));
                nodeSearchGroup.Add(processType, splitCacheArray[1], type);
                return;
            }
            //只在当前分类下
            searchEntryList.Add(new NodeSearchEntry(processType, path, level + 1, type));
        }

        public void GetSearchTreeEntryList(Type processType, List<SearchTreeEntry> result)
        {
            int lastCount = result.Count;
            foreach (var searchGroupItem in searchGroupDictionary) searchGroupItem.Value.GetSearchTreeEntryList(processType, result);

            foreach (var searchEntry in searchEntryList)
            {
                SearchTreeEntry searchTreeEntry = searchEntry.GetSearchTreeEntry(processType);
                if (searchTreeEntry != null) result.Add(searchTreeEntry);
            }

            if (result.Count - lastCount == 0) return;
            if (cache == null) cache = new SearchTreeGroupEntry(new GUIContent(name), level);
            result.Insert(lastCount, cache);
        }

        private bool SplitOnce(string str)
        {
            for (int i = 0, length = str.Length; i < length; i++)
            {
                if (str[i] == '/')
                {
                    splitCacheArray[0] = str[..i];
                    splitCacheArray[1] = str[(i + 1)..];
                    return true;
                }
            }
            return false;
        }
    }
}